package com.zmm.myyimixian.ui.activity.main.fenlei;


import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zmm.myyimixian.MyApp;
import com.zmm.myyimixian.R;
import com.zmm.myyimixian.base.BaseFragment;
import com.zmm.myyimixian.bean.FenLeiTitle;
import com.zmm.myyimixian.bean.FenLeiTitleItem;
import com.zmm.myyimixian.db.DataDao;
import com.zmm.myyimixian.db.ShoppingCart;
import com.zmm.myyimixian.ui.adapter.MyFLTitleApater;
import com.zmm.myyimixian.ui.adapter.MyFeiLeiChildApater;
import com.zmm.myyimixian.util.UIManager;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * A simple {@link Fragment} subclass.
 */
public class FeiLeiFragment extends BaseFragment implements MyFeiLeiChildApater.ModifyCountInterface {

    private int ItemCount = 0;
    private MyHandler handler = new MyHandler(this);
    private boolean isSJK = true;
    //搜索
    @BindView(R.id.fl_ss_iv)
    ImageView flSsIv;
    //定位
    @BindView(R.id.fl_dw_tv)
    TextView flDwTv;
    //标题id
    @BindView(R.id.feilei_title_lv)
    ListView feileiTitleLv;
    //pull_listview
    @BindView(R.id.feilei_tm_prlv)
    PullToRefreshListView feileiTmPrlv;
    private MyFLTitleApater apater;
    private List<FenLeiTitle.CategoriesBean> categories;
    private ListView refreshableView;
    private MyFeiLeiChildApater apater1;
    private List<FenLeiTitleItem.GoodsBean> goods;
    private String shuiGuoId = "51";

    public FeiLeiFragment() {
        // Required empty public constructor
    }

    @Override
    public void initView(View view) {
        refreshableView = feileiTmPrlv.getRefreshableView();
        new MyFenLeiTitleThread(handler).start();
        apater = new MyFLTitleApater(getActivity());
        apater1 = new MyFeiLeiChildApater();
        //点击事件
        feileiTitleLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MyApp.isSJK = true;
                apater.changeSelected(position);
                shuiGuoId = categories.get(position).getId();
                new MyFenLeiTitleItemThread(handler, shuiGuoId).start();
            }
        });
        refreshableView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FenLeiTitleItem.GoodsBean goodsBean = goods.get(position - 1);
                String desc_url = goodsBean.getDesc_url();
                if ("1".equals(goodsBean.getIs_buying_group())) {
                    UIManager.startGroupPurchase(getActivity(), desc_url);
                } else {
                    UIManager.startDetails(getActivity(), desc_url);
                }
            }
        });
        initData();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_fei_lei;
    }

    //数量的加和初始创建
    @Override
    public void doIncrease(int position, TextView showCountView, ImageButton jian, ImageButton jia, int count) {
        MyApp.isSJK = false;
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        FenLeiTitleItem.GoodsBean goodsBean = goods.get(position);
        if (ItemCount == 0) {
            ItemCount = 1;
            jian.setVisibility(View.VISIBLE);
            showCountView.setVisibility(View.VISIBLE);
            showCountView.setText("1");
            apater1.notifyDataSetChanged();
            DataDao.addShoppingCart(goodsBean.getImg(), goodsBean.getName(), goodsBean.getUnit_desc(), goodsBean.getUnit_price(), "1", goodsBean.getPromotion_img(), new SaveListener() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onFailure(int i, String s) {
                    Toast.makeText(getActivity(), "没有网络", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            ++ItemCount;
            String valueOf = String.valueOf(ItemCount);
            showCountView.setText(valueOf);
            apater1.notifyDataSetChanged();
            DataDao.setShoppingCart(goodsBean.getName(), valueOf);
        }
    }

    @Override
    public void doDecrease(int position, final TextView showCountView, final ImageButton jian, ImageButton jia, int count) {
        MyApp.isSJK = false;
        String deletname = goods.get(position).getName();
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        --ItemCount;
        final String text = String.valueOf(ItemCount);
        if (ItemCount < 1) {
            DataDao.deleteShoppingCart(goods.get(position).getName(), new DeleteListener() {
                @Override
                public void onSuccess() {
                    MyApp.isSJK = true;
                }

                @Override
                public void onFailure(int i, String s) {

                }
            });
            showCountView.setText(text);
            jian.setVisibility(View.GONE);
            showCountView.setVisibility(View.GONE);
            apater1.notifyDataSetChanged();
        } else {
            showCountView.setText(text);
            apater1.notifyDataSetChanged();
            DataDao.setShoppingCart(deletname, text);
        }
    }


    @OnClick(R.id.fl_ss_iv)
    public void onClick() {
        //跳转到搜索界面
        UIManager.startSearchActivity(getFActivity());
    }


    //获取网上下载的数据
    private class MyHandler extends Handler {

        private WeakReference<FeiLeiFragment> reference = null;

        public MyHandler(FeiLeiFragment feiLeiFragment) {
            reference = new WeakReference<>(feiLeiFragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FeiLeiFragment feiLeiFragment = reference.get();
            if (feiLeiFragment != null) {
                if (msg.what == 1) {
                    FenLeiTitle fenLeiTitle = (FenLeiTitle) msg.obj;
                    categories = fenLeiTitle.getCategories();
                    apater.setData(categories);
                    feileiTitleLv.setAdapter(apater);
                    String id = categories.get(0).getId();
                    shuiGuoId = id;
                    new MyFenLeiTitleItemThread(handler, id).start();
                } else if (msg.what == 2) {
                    FenLeiTitleItem fenLeiTitleItem = (FenLeiTitleItem) msg.obj;
                    goods = fenLeiTitleItem.getGoods();
                    initData(goods);
                }
            }
        }

        private void initData(List<FenLeiTitleItem.GoodsBean> goods) {
            apater1.setData(goods);
            apater1.setModifyCountInterface(FeiLeiFragment.this);
            refreshableView.setAdapter(apater1);
        }
    }

    //获得购物车数据库数据
    private void initData() {
        if (MyApp.isLogin()) {
            MyApp.isSJK = true;
            DataDao.getAllShoppingCarts(new FindListener<ShoppingCart>() {
                @Override
                public void onSuccess(List<ShoppingCart> list) {
                    apater1.setShuJuKu(list);
                }

                @Override
                public void onError(int i, String s) {

                }
            });
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (MyApp.isLogin()) {
            initData();
        }
    }
}
